/**
 * Tempranillo
 *
 * A client side implementation of the CodeIgniter form validation
 * configuration in jQuery by Jeroen van der Tuin.
 */
(function($) {

$.fn.tempranillo = function(options) {

var defaults = {
	"url": '/tempranillo'
};

options = $.extend(defaults, options);

return this.each(function() {
	var form = $(this);

	/**
	 * A flag that is true if the form should be submitted immediatly
	 * or false if it has to be validated first.
	 */
	var validated = false;

	/**
	 * Validate the whole form before submit and .
	 */
	form.bind('submit', function() {
		// Submit the form immediatly if it has already been validated.
		if (validated) {
			return true;
		}

		var form = $(this);

		$.ajax({
			"type": "POST",
			"url": options.url + '/form/' + form.attr('id'),
			"data": form.serialize(),
			"dataType": 'json',
			"success": function(data, status) {
				if (data.error == '') {
					validated = true;
					$(this).submit();
					return;
				}

				$('#error_' + form.attr('id')).html(data.error).show();
			}
		});

		// Don't submit the form.
		return false;

	});

	/**
	 * Sends only one input field to the server for validation.
	 *
	 * The reason that every field is checked is to be able to display
	 * the error that the framework supplies and that there is no
	 * difference between server and client side validation.
	 *
	 * The controller reads the form validation configuration file
	 * and only sets that single rule for validation.
	 */
	$('input', form).bind('change', function() {
		var input = $(this);
		var name = input.attr('name');

		var data = {
			"form": form.attr('id'),
			"field": name
		};

		data[name] = input.val();

		$.ajax({
			"type": "POST",
			"url": options.url + '/field/',
			"data": data,
			"dataType": 'json',
			"success": function(data, status) {
				var selector = form.attr('id') + '_' + name;

				if (data.error == '') {
					$('#valid_' + selector).show();
					return;
				}

				$('#valid_' + selector).hide();

				// Show error at input field.
				$('#error_' + form.attr('id') + '_' + name)
					.html(data.error)
					.show();
			}
		});
	});
});

}})(jQuery);